import { ref, watch } from 'vue';
import { TAB_LIST } from '../utils/constant';
import { pages } from '@/router';

type TabItem = {
  name: string;
  path: string;
  title: string;
};

function findInObjectArrayTree(nodes, name) {
  for (const node of nodes) {
    if (node.name === name) {
      return node;
    }
    if (node.children) {
      const result = findInObjectArrayTree(node.children, name);
      if (result) {
        return result;
      }
    }
  }

  return null;
}

export const useTabList = () => {
  const tabs = ref<TabItem[]>(JSON.parse(localStorage.getItem(TAB_LIST) || '[]'));

  function update() {
    localStorage.setItem(TAB_LIST, JSON.stringify(tabs.value));
  }

  function removeTabList() {
    localStorage.removeItem(TAB_LIST);
  }

  function addTabItem(item: TabItem) {
    let idx = tabs.value.findIndex((v) => v.name === item.name);
    if (idx === -1) {
      tabs.value.push(item);
    }
  }

  function removeTabItem(name) {
    let idx = tabs.value.findIndex((v) => v.name === name);
    if (idx >= 0) {
      tabs.value.splice(idx, 1);
    }
    return idx;
  }

  function clearTabs(current) {
    tabs.value = [];
    tabs.value.push(current);
  }

  function getIcon(name) {
    const page = findInObjectArrayTree(pages, name);

    if (page && page.meta.icon) {
      return page.meta.icon;
    }
  }

  watch(
    () => tabs.value.length,
    () => {
      update();
    }
  );

  return {
    tabs,
    removeTabList,
    addTabItem,
    removeTabItem,
    clearTabs,
    getIcon
  };
};
